"""
使用DeepSeek API的完整版服务
"""
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
import json
from datetime import datetime, timedelta
import openai
from complete_railway_api import RailwayAPI

app = Flask(__name__)
CORS(app)

# 使用你的DeepSeek API密钥
DEEPSEEK_API_KEY = "sk-00d9e28b0be74eb4b070a062b7cb73b7"  # 你的真实API密钥
DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1"
DEEPSEEK_MODEL = "deepseek-chat"
GAODE_API_KEY = "003df4ac18f1cca97eaf59dc90afbaa2"

class DeepSeekDataAPI:
    def __init__(self):
        self.gaode_key = GAODE_API_KEY
        self.base_url = "https://restapi.amap.com/v3"
        self.railway_api = RailwayAPI()
        
        # 初始化DeepSeek AI客户端
        try:
            self.ai_client = openai.OpenAI(
                api_key=DEEPSEEK_API_KEY,
                base_url=DEEPSEEK_BASE_URL
            )
            self.ai_model = DEEPSEEK_MODEL
            self.ai_available = True
            print("✅ DeepSeek AI 客户端初始化成功")
        except Exception as e:
            print(f"❌ DeepSeek AI 客户端初始化失败: {e}")
            self.ai_client = None
            self.ai_available = False
    
    def geocode(self, address):
        """地理编码"""
        clean_address = address.replace('从', '').replace('出发', '').replace('到', '').replace('去', '').strip()
        
        url = f"{self.base_url}/geocode/geo"
        search_attempts = [
            clean_address,
            address,
            f"{clean_address} 中国",
        ]
        
        if '大连' in clean_address:
            search_attempts.append(f"{clean_address} 大连")
            search_attempts.append("大连")
        if '合肥' in clean_address:
            search_attempts.append(f"{clean_address} 合肥")
            search_attempts.append("合肥")
        
        for search_address in search_attempts:
            try:
                params = {
                    'key': self.gaode_key,
                    'address': search_address,
                    'output': 'json'
                }
                
                print(f"尝试地理编码: {search_address}")
                response = requests.get(url, params=params, timeout=10)
                
                if response.status_code == 200:
                    data = response.json()
                    if data.get('status') == '1' and data.get('geocodes'):
                        geocode = data['geocodes'][0]
                        location = geocode.get('location', '').split(',')
                        if len(location) == 2:
                            return {
                                'success': True,
                                'location': {
                                    'lng': float(location[0]),
                                    'lat': float(location[1])
                                },
                                'formatted_address': geocode.get('formatted_address', ''),
                                'address': geocode.get('address', ''),
                                'city': geocode.get('city', ''),
                                'district': geocode.get('district', ''),
                                'province': geocode.get('province', '')
                            }
                print(f"地理编码失败: {search_address}")
            except Exception as e:
                print(f"地理编码异常: {search_address} - {e}")
                continue
        
        return {'success': False, 'error': f'无法解析地址: {address}'}
    
    def search_poi(self, query, city=None):
        """POI搜索"""
        url = f"{self.base_url}/place/text"
        params = {
            'key': self.gaode_key,
            'keywords': query,
            'output': 'json',
            'extensions': 'all'
        }
        
        if city:
            params['city'] = city
        
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('status') == '1' and data.get('pois'):
                    pois = []
                    for poi in data['pois'][:10]:
                        pois.append({
                            'id': poi.get('id', ''),
                            'name': poi.get('name', ''),
                            'type': poi.get('type', ''),
                            'address': poi.get('address', ''),
                            'location': poi.get('location', ''),
                            'tel': poi.get('tel', ''),
                            'distance': poi.get('distance', '')
                        })
                    return {
                        'success': True,
                        'pois': pois
                    }
                else:
                    return {
                        'success': False,
                        'error': '未找到相关地点'
                    }
            else:
                return {
                    'success': False,
                    'error': f'请求失败: {response.status_code}'
                }
        except Exception as e:
            return {
                'success': False,
                'error': f'POI搜索异常: {str(e)}'
            }
    
    def get_weather(self, city):
        """获取天气信息"""
        url = f"{self.base_url}/weather/weatherInfo"
        params = {
            'key': self.gaode_key,
            'city': city,
            'output': 'json'
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('status') == '1' and data.get('lives'):
                    weather = data['lives'][0]
                    return {
                        'success': True,
                        'weather': {
                            'city': weather.get('city', ''),
                            'weather': weather.get('weather', ''),
                            'temperature': weather.get('temperature', ''),
                            'humidity': weather.get('humidity', ''),
                            'wind_power': weather.get('windpower', ''),
                            'wind_direction': weather.get('winddirection', ''),
                            'report_time': weather.get('reporttime', '')
                        }
                    }
                else:
                    return {
                        'success': False,
                        'error': '天气信息获取失败'
                    }
            else:
                return {
                    'success': False,
                    'error': f'请求失败: {response.status_code}'
                }
        except Exception as e:
            return {
                'success': False,
                'error': f'天气查询异常: {str(e)}'
            }
    
    def get_ai_response(self, message, context=None):
        """获取AI回复"""
        if not self.ai_available or not self.ai_client:
            print("AI服务不可用，使用备用回复")
            return self.get_fallback_response(message)
        
        try:
            system_prompt = """你是一个专业的旅行规划AI助手，专门帮助用户规划出行路线。你的主要功能包括：

1. 路线规划：根据用户提供的出发地和目的地，推荐最佳的出行方案（高铁、飞机、汽车等）
2. 天气查询：提供目的地的天气信息
3. 地点搜索：帮助用户搜索感兴趣的地点
4. 出行建议：根据用户需求提供个性化的出行建议

请用友好、专业的语气回复用户，并提供实用的建议。如果用户询问路线规划，请引导他们使用搜索功能。"""
            
            response = self.ai_client.chat.completions.create(
                model=self.ai_model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": message}
                ],
                max_tokens=1000,
                temperature=0.7
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            print(f"DeepSeek AI调用失败: {e}")
            return self.get_fallback_response(message)
    
    def get_fallback_response(self, message):
        """备用回复"""
        if '路线' in message or '到' in message:
            return "🚀 我可以帮您规划出行路线！\n\n请使用上方的搜索框输入：\n• 出发地：如'大连'或'大连交通大学'\n• 目的地：如'合肥'或'合肥南站'\n\n然后点击'搜索路线'按钮，我会为您提供多种出行方案！"
        elif '天气' in message:
            return "🌤️ 我可以帮您查询天气信息！\n\n请告诉我您想查询哪个城市的天气，比如：\n• 查询北京天气\n• 查询上海天气\n• 查询大连天气"
        elif '搜索' in message or '找' in message:
            return "🔍 我可以帮您搜索地点信息！\n\n请在上方搜索框中输入您要找的地点，比如：\n• 火车站\n• 机场\n• 酒店\n• 景点"
        else:
            return "👋 您好！我是您的出行助手！\n\n我可以帮您：\n• 🚄 规划出行路线\n• 🌤️ 查询天气信息\n• 🔍 搜索地点信息\n• 🗺️ 显示地图路线\n\n请告诉我您需要什么帮助！"
    
    def generate_routes(self, origin, destination):
        """生成路线方案"""
        # 首先尝试获取真实的高铁数据
        real_trains = self.railway_api.search_trains(origin, destination)
        
        if real_trains['success'] and real_trains['trains']:
            print(f"成功获取到 {len(real_trains['trains'])} 条真实高铁数据")
            routes = []
            
            for train in real_trains['trains'][:3]:  # 取前3条
                route = {
                    'total_time': self._calculate_duration(train['departure_time'], train['arrival_time']),
                    'total_price': self._estimate_price(train['train_number']),
                    'transfers': 0,
                    'details': [{
                        'type': 'high_speed_rail',
                        'origin': origin,
                        'destination': destination,
                        'departure_time': train['departure_time'],
                        'arrival_time': train['arrival_time'],
                        'price': self._estimate_price(train['train_number']),
                        'train_number': train['train_number'],
                        'can_buy': train['can_buy'],
                        'description': f'高铁直达，{train["duration"]}'
                    }]
                }
                routes.append(route)
            
            return routes
        
        # 如果真实数据获取失败，使用增强模拟数据
        print("使用增强模拟数据")
        routes = []
        
        # 高铁直达
        routes.append({
            'total_time': 2.5,
            'total_price': 150,
            'transfers': 0,
            'details': [{
                'type': 'high_speed_rail',
                'origin': origin,
                'destination': destination,
                'departure_time': '08:00',
                'arrival_time': '10:30',
                'price': 150,
                'train_number': 'G1234',
                'can_buy': True,
                'description': '高铁直达，舒适便捷'
            }]
        })
        
        # 高铁中转
        routes.append({
            'total_time': 3.2,
            'total_price': 120,
            'transfers': 1,
            'details': [
                {
                    'type': 'high_speed_rail',
                    'origin': origin,
                    'destination': '南京南',
                    'departure_time': '08:30',
                    'arrival_time': '10:00',
                    'price': 80,
                    'train_number': 'G1235',
                    'can_buy': True,
                    'description': '第一段：高铁'
                },
                {
                    'type': 'high_speed_rail',
                    'origin': '南京南',
                    'destination': destination,
                    'departure_time': '10:30',
                    'arrival_time': '11:50',
                    'price': 40,
                    'train_number': 'G1236',
                    'can_buy': True,
                    'description': '第二段：高铁'
                }
            ]
        })
        
        # 飞机直达
        routes.append({
            'total_time': 4.0,
            'total_price': 280,
            'transfers': 0,
            'details': [{
                'type': 'flight',
                'origin': origin,
                'destination': destination,
                'departure_time': '09:00',
                'arrival_time': '13:00',
                'price': 280,
                'flight_number': 'CA1234',
                'can_buy': True,
                'description': '飞机直达，快速舒适'
            }]
        })
        
        return routes
    
    def _calculate_duration(self, departure, arrival):
        """计算行程时间"""
        try:
            dep_time = datetime.strptime(departure, '%H:%M')
            arr_time = datetime.strptime(arrival, '%H:%M')
            
            if arr_time < dep_time:  # 跨天
                arr_time = arr_time.replace(day=arr_time.day + 1)
            
            duration = (arr_time - dep_time).total_seconds() / 3600
            return round(duration, 1)
        except:
            return 2.5
    
    def _estimate_price(self, train_number):
        """估算票价"""
        if train_number.startswith('G'):
            return 150
        elif train_number.startswith('D'):
            return 120
        elif train_number.startswith('C'):
            return 100
        else:
            return 80

# 初始化API实例
deepseek_api = DeepSeekDataAPI()

@app.route('/api/test', methods=['GET'])
def test():
    return jsonify({
        'success': True,
        'message': 'DeepSeek API服务运行正常',
        'timestamp': datetime.now().isoformat()
    })

@app.route('/api/status', methods=['GET'])
def status():
    return jsonify({
        'success': True,
        'status': 'online',
        'version': '3.0.0',
        'apis': {
            'gaode': 'available',
            'railway': 'available',
            'ai': 'available' if deepseek_api.ai_available else 'unavailable'
        },
        'timestamp': datetime.now().isoformat()
    })

@app.route('/api/cities', methods=['GET'])
def get_cities():
    """获取城市列表"""
    cities_list = [
        {'id': 1, 'name': '北京', 'code': 'BJP', 'level': 'province'},
        {'id': 2, 'name': '上海', 'code': 'SHH', 'level': 'province'},
        {'id': 3, 'name': '广州', 'code': 'GZQ', 'level': 'province'},
        {'id': 4, 'name': '深圳', 'code': 'SZQ', 'level': 'province'},
        {'id': 5, 'name': '杭州', 'code': 'HZH', 'level': 'province'},
        {'id': 6, 'name': '南京', 'code': 'NJH', 'level': 'province'},
        {'id': 7, 'name': '武汉', 'code': 'WHN', 'level': 'province'},
        {'id': 8, 'name': '成都', 'code': 'CDW', 'level': 'province'},
        {'id': 9, 'name': '西安', 'code': 'XAY', 'level': 'province'},
        {'id': 10, 'name': '重庆', 'code': 'CQW', 'level': 'province'},
        {'id': 11, 'name': '天津', 'code': 'TJP', 'level': 'province'},
        {'id': 12, 'name': '青岛', 'code': 'QDK', 'level': 'province'},
        {'id': 13, 'name': '大连', 'code': 'DLT', 'level': 'province'},
        {'id': 14, 'name': '合肥', 'code': 'HFH', 'level': 'province'},
        {'id': 42, 'name': '大连交通大学', 'code': 'DLT', 'level': 'university'},
        {'id': 43, 'name': '合肥南站', 'code': 'ENH', 'level': 'station'},
    ]
    
    return jsonify({
        'success': True,
        'cities': cities_list,
        'source': f'城市数据库（包含{len(cities_list)}个城市）',
        'total': len(cities_list)
    })

@app.route('/api/search', methods=['POST'])
def search():
    """路线搜索"""
    data = request.get_json()
    origin = data.get('origin', '')
    destination = data.get('destination', '')
    
    if not origin or not destination:
        return jsonify({
            'success': False,
            'error': '请提供出发地和目的地'
        })
    
    print(f"正在搜索: {origin} -> {destination}")
    
    # 地理编码
    origin_geocode = deepseek_api.geocode(origin)
    destination_geocode = deepseek_api.geocode(destination)
    
    print(f"出发地编码结果: {origin_geocode}")
    print(f"目的地编码结果: {destination_geocode}")
    
    # 生成路线
    routes = deepseek_api.generate_routes(origin, destination)
    
    return jsonify({
        'success': True,
        'routes': routes,
        'message': f'为您找到 {len(routes)} 条路线',
        'origin_info': origin_geocode,
        'destination_info': destination_geocode
    })

@app.route('/api/chat', methods=['POST'])
def chat():
    """AI聊天接口"""
    data = request.get_json()
    message = data.get('message', '')
    
    if not message:
        return jsonify({
            'success': False,
            'error': '请提供消息内容'
        })
    
    # 获取AI回复
    response = deepseek_api.get_ai_response(message)
    
    # 生成建议
    suggestions = []
    if '路线' in message or '到' in message:
        suggestions = ['从北京到上海', '从广州到深圳', '从杭州到南京']
    elif '天气' in message:
        suggestions = ['查询北京天气', '查询上海天气', '查询广州天气']
    else:
        suggestions = ['查询天气', '规划路线', '搜索地点']
    
    return jsonify({
        'success': True,
        'response': response,
        'suggestions': suggestions,
        'ai_model': 'DeepSeek Chat' if deepseek_api.ai_available else '智能AI助手'
    })

@app.route('/api/weather', methods=['GET', 'POST'])
def weather():
    """天气查询接口"""
    if request.method == 'GET':
        city = request.args.get('city', '')
    else:
        data = request.get_json()
        city = data.get('city', '')
    
    if not city:
        return jsonify({
            'success': False,
            'error': '请提供城市名称'
        })
    
    result = deepseek_api.get_weather(city)
    return jsonify(result)

@app.route('/api/poi', methods=['POST'])
def poi():
    """POI搜索接口"""
    data = request.get_json()
    query = data.get('query', '')
    
    if not query:
        return jsonify({
            'success': False,
            'error': '请提供搜索关键词'
        })
    
    result = deepseek_api.search_poi(query)
    return jsonify(result)

@app.route('/api/trains', methods=['POST'])
def trains():
    """高铁查询接口"""
    data = request.get_json()
    from_station = data.get('from_station', '')
    to_station = data.get('to_station', '')
    date = data.get('date', '')
    
    if not from_station or not to_station:
        return jsonify({
            'success': False,
            'error': '请提供出发站和到达站'
        })
    
    result = deepseek_api.railway_api.search_trains(from_station, to_station, date)
    return jsonify(result)

if __name__ == '__main__':
    print("🚀 启动DeepSeek API集成服务...")
    print("📍 高德地图API: 已配置")
    print("🚄 12306铁路API: 已配置")
    print("🤖 DeepSeek AI: 已配置" if deepseek_api.ai_available else "🤖 DeepSeek AI: 未配置")
    print("🌐 服务地址: http://localhost:5000")
    print("📋 API文档: http://localhost:5000/api/status")
    app.run(debug=True, host='0.0.0.0', port=5000)